package com.cheyun.netsalev3

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import android.widget.ListView
import android.widget.PopupWindow
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import com.cheyun.netsalev3.databinding.ConversationFragmentBinding
import com.cheyun.netsalev3.tencenttim.chat.ChatActivity
import com.cheyun.netsalev3.tencenttim.menu.Menu
import com.cheyun.netsalev3.tencenttim.profile.MyInfoActivity
import com.cheyun.netsalev3.tencenttim.signature.GenerateTestUserSig
import com.cheyun.netsalev3.tencenttim.thirdpush.ThirdPushTokenMgr
import com.cheyun.netsalev3.tencenttim.utils.Constants
import com.cheyun.netsalev3.tencenttim.utils.DemoLog
import com.cheyun.netsalev3.utils.BaseFragment
import com.cheyun.netsalev3.utils.InjectorUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.utils.api.DmApiClient
import com.cheyun.netsalev3.utils.api.DmBaseResp
import com.cheyun.netsalev3.utils.api.dm.DmApiCallback
import com.cheyun.netsalev3.utils.api.dm.DmApiException
import com.cheyun.netsalev3.viewmodel.DmChatViewModel
import com.jeremyliao.liveeventbus.LiveEventBus
import com.tencent.imsdk.TIMConversationType
import com.tencent.qcloud.tim.uikit.TUIKit
import com.tencent.qcloud.tim.uikit.base.IMEventListener
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack
import com.tencent.qcloud.tim.uikit.component.TitleBarLayout
import com.tencent.qcloud.tim.uikit.component.action.PopActionClickListener
import com.tencent.qcloud.tim.uikit.component.action.PopDialogAdapter
import com.tencent.qcloud.tim.uikit.component.action.PopMenuAction
import com.tencent.qcloud.tim.uikit.modules.chat.GroupChatManagerKit
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationManagerKit
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationProvider
import com.tencent.qcloud.tim.uikit.modules.conversation.base.ConversationInfo
import com.tencent.qcloud.tim.uikit.utils.FileUtil
import com.tencent.qcloud.tim.uikit.utils.PopWindowUtil
import com.tencent.qcloud.tim.uikit.utils.ToastUtil
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.ArrayList


class DmChatFragment() : BaseFragment<ConversationFragmentBinding>() , ConversationManagerKit.MessageUnreadWatcher  {
    override fun updateUnread(count: Int) {
        LiveEventBus.get().with("chatNum").postValue(count)
    }
    companion object {
        fun newInstance() = DmChatFragment()
    }

    override fun initContentView(): Int {
        return R.layout.conversation_fragment
    }

    private var mBaseView: View? = null
    private var mConversationPopList: ListView? = null
    private var mConversationPopAdapter: PopDialogAdapter? = null
    private var mConversationPopWindow: PopupWindow? = null
    private val mConversationPopActions = ArrayList<PopMenuAction>()
    private var mMenu: Menu? = null
    private var mActivity:Activity? = null
    private var online = true

    init {
    }

    override fun initViewModel(): ViewModel? {
        activity?.apply {
            val factory = InjectorUtils.getDmChatViewModelFactory()
            return ViewModelProviders.of(this, factory).get(DmChatViewModel::class.java)
        }
        return null
    }

    override fun initData() {
        mActivity = this.activity
        TUIKit.addIMEventListener(mIMEventListener);
//        if(MyApplication.getInstance().getTimOffline()){
//            changeOnlineStatus(false,true)
//        }
        changeOnlineStatus(MyApplication.getInstance().getTimBusying(), true, MyApplication.getInstance().getTimOffline())

        getKefuList()

        binding.viewModel?.data?.observe(this, Observer { list ->
            ConversationManagerKit.getInstance().loadConversation(object : IUIKitCallBack {
                override fun onSuccess(data: Any) {
                    var s = data as ConversationProvider
                    var oldList = s.dataSource
                    var newList = ArrayList<ConversationInfo>()

                    for (i in 0 until  oldList.size) {
                        var has = false
                        var id = oldList.get(i).id
                        for (k in 0 until  list.size) {
                            if (list.get(k).phone.equals(id)) {
                                has = true
                            }
                        }
                        if (has) {
                            newList.add(oldList.get(i))
                        }
                    }
                    s.dataSource = newList
                    binding.conversationLayout.getConversationList().adapter?.setDataProvider(s)
                }

                override fun onError(module: String, errCode: Int, errMsg: String) {

                }
            })
        })
    }

    override fun lazyInit() {
        Log.i(TAG,"override lazyinit")
    }

    // 监听做成静态可以让每个子类重写时都注册相同的一份。
    private val mIMEventListener = object : IMEventListener() {
        override fun onForceOffline() {
            changeOnlineStatus(false,false,true)
            sendBusyInfo("1")
        }
    }

    fun changeOnlineStatus(busying:Boolean,owner:Boolean,offLine:Boolean){
        if(!busying){
            binding.lyOffline.visibility = View.GONE
            binding.txtOnline.text = "在线"
            binding.sV.isChecked = true
        }else{
            binding.txtOnline.text = "下线"
            binding.sV.isChecked = false
        }
        online = !offLine
        if(offLine){
            binding.sV.isChecked = false
            binding.txtOnline.text = "下线"
            if(!owner){
                ToastUtil.toastLongMessage("您的帐号已在其它终端登录,请重新登录")
            }
            binding.lyOffline.visibility = View.VISIBLE
        }
        MyApplication.getInstance().setTimBusying(busying)
        MyApplication.getInstance().setTimOffline(offLine)
    }

    fun sendBusyInfo(status:String){
        DmApiClient.getInstance().kefuBusy(MySharedPreferences.getMobile(),status)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DmApiCallback<DmBaseResp<Any, Any>>() {
                    override fun onSuccess(t: DmBaseResp<Any, Any>) {

                    }

                    override fun onError(ex: DmApiException) {

                    }
                })
    }
    override fun initView() {
        // 从布局文件中获取会话列表面板
        mMenu = Menu(activity, binding.conversationLayout.getTitleBar() as TitleBarLayout, Menu.MENU_TYPE_CONVERSATION)
        // 会话列表面板的默认UI和交互初始化
        binding.conversationLayout.initDefault()
        // 通过API设置ConversataonLayout各种属性的样例，开发者可以打开注释，体验效果
//        ConversationLayoutHelper.customizeConversation(mConversationLayout);
        binding.conversationLayout.getConversationList().setOnItemClickListener { view, position, conversationInfo ->
            //此处为demo的实现逻辑，更根据会话类型跳转到相关界面，开发者可根据自己的应用场景灵活实现
            startChatActivity(conversationInfo)
        }
        binding.conversationLayout.getConversationList().setOnItemLongClickListener { view, position, conversationInfo -> startPopShow(view, position, conversationInfo) }

        initTitleAction()
        initPopMenuAction()

        FileUtil.initPath() // 从application移入到这里，原因在于首次装上app，需要获取一系列权限，如创建文件夹，图片下载需要指定创建好的文件目录，否则会下载本地失败，聊天页面从而获取不到图片、表情
        // 未读消息监视器
        ConversationManagerKit.getInstance().addUnreadWatcher(this)
        GroupChatManagerKit.getInstance()

        binding.sV.setOnCheckedChangeListener { buttonView, isChecked -> if(isChecked){
//            timLogin()
            if(MyApplication.getInstance().getTimOffline()){
//                下线状态切换至上线
                timLogin()
            }
            sendBusyInfo("0")
            changeOnlineStatus(false,true,MyApplication.getInstance().getTimOffline())
        }else{
//            timLoginOut()
            sendBusyInfo("1")
            changeOnlineStatus(true,true,MyApplication.getInstance().getTimOffline())
        }}
        binding.lyOffline.setOnClickListener(null)
        binding.leftBut.setOnClickListener({view->
            this.activity?.finish()
        })
    }

    fun getKefuList(){
        if(MyApplication.getInstance().getTimOffline()){
           return
        }
        binding.viewModel?.getKefuList();
    }

    fun timLogin(){
        var mobile = MySharedPreferences.getMobile()
        val userSig = GenerateTestUserSig.genTestUserSig(mobile)
        TUIKit.login(mobile, userSig, object : IUIKitCallBack {
            override fun onError(module: String, code: Int, desc: String) {
                DemoLog.i("tim login", "imLogin errorCode = $code, errorInfo = $desc")
            }

            override fun onSuccess(data: Any?) {
                DemoLog.i("tim login", "imLogin success")
                changeOnlineStatus(false,true,false)
                getKefuList()
                ThirdPushTokenMgr.getInstance().setPushTokenToTIM();
            }
        })
    }
//
//    fun timLoginOut(){
//        TIMManager.getInstance().logout(object : TIMCallBack {
//            override fun onError(code: Int, desc: String) {
//                ToastUtil.toastLongMessage("logout fail: $code=$desc")
//                logout()
//            }
//
//            override fun onSuccess() {
//                logout()
//            }
//
//            private fun logout() {
//                TUIKit.unInit()
//                changeOnlineStatus(false,true)
//            }
//        })
//    }

    private fun initTitleAction() {
        var titleBarLayout = binding.conversationLayout.getTitleBar()
//        titleBarLayout.setTitle("消息", ITitleBarLayout.POSITION.MIDDLE)
//        titleBarLayout.setOnRightClickListener {
//            if (mMenu?.isShowing()!!) {
//                mMenu?.hide()
//            } else {
//                mMenu?.show()
//            }
//        }
        titleBarLayout.visibility = View.GONE
        binding.rightImg.setOnClickListener({v->
            if(online) {
                val intent = Intent(MyApplication.getInstance(), MyInfoActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                MyApplication.getInstance().startActivity(intent)
            }else{

            }
        })
    }

    private fun initPopMenuAction() {
        // 设置长按conversation显示PopAction
        val conversationPopActions = ArrayList<PopMenuAction>()
        var action = PopMenuAction()
        action.actionName = resources.getString(R.string.chat_top)
        action.actionClickListener = PopActionClickListener { position, data -> binding.conversationLayout.setConversationTop(position, data as ConversationInfo) }
        conversationPopActions.add(action)
        action = PopMenuAction()
        action.actionClickListener = PopActionClickListener { position, data -> binding.conversationLayout.deleteConversation(position, data as ConversationInfo) }
        action.actionName = resources.getString(R.string.chat_delete)
        conversationPopActions.add(action)
        mConversationPopActions.clear()
        mConversationPopActions.addAll(conversationPopActions)
    }

    /**
     * 长按会话item弹框
     *
     * @param index            会话序列号
     * @param conversationInfo 会话数据对象
     * @param locationX        长按时X坐标
     * @param locationY        长按时Y坐标
     */
    private fun showItemPopMenu(index: Int, conversationInfo: ConversationInfo, locationX: Float, locationY: Float) {
        if (mConversationPopActions == null || mConversationPopActions.size == 0)
            return
        val itemPop = LayoutInflater.from(activity).inflate(R.layout.pop_menu_layout, null)
        mConversationPopList = itemPop.findViewById(R.id.pop_menu_list)
        mConversationPopList?.setOnItemClickListener(AdapterView.OnItemClickListener { parent, view, position, id ->
            val action = mConversationPopActions[position]
            if (action.actionClickListener != null) {
                action.actionClickListener.onActionClick(index, conversationInfo)
            }
            mConversationPopWindow?.dismiss()
        })

        for (i in mConversationPopActions.indices) {
            val action = mConversationPopActions[i]
            if (conversationInfo.isTop) {
                if (action.actionName == resources.getString(R.string.chat_top)) {
                    action.actionName = resources.getString(R.string.quit_chat_top)
                }
            } else {
                if (action.actionName == resources.getString(R.string.quit_chat_top)) {
                    action.actionName = resources.getString(R.string.chat_top)
                }
            }
        }
        mConversationPopAdapter = PopDialogAdapter()
        mConversationPopList?.setAdapter(mConversationPopAdapter)
        mConversationPopAdapter?.setDataSource(mConversationPopActions)
        mConversationPopWindow = PopWindowUtil.popupWindow(itemPop, mBaseView, locationX.toInt(), locationY.toInt())
        binding.root.postDelayed(Runnable { mConversationPopWindow?.dismiss() }, 10000) // 10s后无操作自动消失
    }

    private fun startPopShow(view: View, position: Int, info: ConversationInfo) {
        showItemPopMenu(position, info, view.x, view.y + view.height / 2)
    }

    private fun startChatActivity(conversationInfo: ConversationInfo) {
        val chatInfo = ChatInfo()
        chatInfo.type = if (conversationInfo.isGroup) TIMConversationType.Group else TIMConversationType.C2C
        chatInfo.id = conversationInfo.id
        chatInfo.chatName = conversationInfo.title
        val intent = Intent(MyApplication.getInstance(), ChatActivity::class.java)
        intent.putExtra(Constants.CHAT_INFO, chatInfo)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        MyApplication.getInstance().startActivity(intent)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        prepareThirdPushToken()
    }

}
